package com.tofine.smarthome.fragment;


import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.activeandroid.query.Select;
import com.tofine.smarthome.R;
import com.tofine.smarthome.adapter.SceneRecyclerViewAdapter;
import com.tofine.smarthome.base.BaseFragment;
import com.tofine.smarthome.model.Device;
import com.tofine.smarthome.model.Scene;
import com.tofine.smarthome.model.SceneDevice;
import com.tofine.smarthome.ui.SceneAddActivity;
import com.tofine.smarthome.util.ResourceUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * @author ddMax
 * @since 2016/4/25
 * 说明：场景碎片类
 */
public class SceneFragment extends BaseFragment {
    public static final String TAG = SceneFragment.class.getSimpleName();

    public static final int ACTION_ADD_SCENE = 0;

    private List<Scene> mSceneData;

    private View view;
    @Bind(R.id.scene_list) RecyclerView mSceneList;
    private RecyclerView.Adapter mAdapter;

    public SceneFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @return A new instance of fragment SceneFragment.
     */
    public static SceneFragment newInstance() {
        SceneFragment fragment = new SceneFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_scene, container, false);
        initData();
        initView();
        return view;
    }

    @Override
    protected void initView() {
        ButterKnife.bind(this, view);

        setUpActionBar();
        setUpSceneList();
    }

    @Override
    protected void initData() {
        if (new Select().from(Scene.class).exists()) {
            mSceneData = new Select().from(Scene.class).execute();
        } else {
            // TODO: Scene本地数据不存在，从网络获取
            Scene[] testSceneData = {
                new Scene(ResourceUtils.getUriToDrawable(getActivity(), R.drawable.ic_scene_sun).toString(), "日常模式", true),
                new Scene(ResourceUtils.getUriToDrawable(getActivity(), R.drawable.ic_scene_out).toString(), "外出模式", false),
                new Scene(ResourceUtils.getUriToDrawable(getActivity(), R.drawable.ic_scene_sleep).toString(), "睡眠模式", false),
                new Scene(ResourceUtils.getUriToDrawable(getActivity(), R.drawable.ic_scene_party).toString(), "派对模式", false),
            };
            mSceneData = new ArrayList<>(Arrays.asList(testSceneData));
            for (Scene scene : mSceneData) {
                scene.save();
            }
        }
        if (!new Select().from(SceneDevice.class).exists()) {
            generateSceneDeviceData();
        }
    }

    private void generateSceneDeviceData() {
        SceneDevice[] sceneDeviceData = {
                new SceneDevice(
                        (Scene) new Select().from(Scene.class).where("name='日常模式'").executeSingle(),
                        (Device) new Select().from(Device.class).where("name='智能插座'").executeSingle()
                ),
                new SceneDevice(
                        (Scene) new Select().from(Scene.class).where("name='日常模式'").executeSingle(),
                        (Device) new Select().from(Device.class).where("name='微波炉'").executeSingle()
                ),
                new SceneDevice(
                        (Scene) new Select().from(Scene.class).where("name='日常模式'").executeSingle(),
                        (Device) new Select().from(Device.class).where("name='洗衣机'").executeSingle()
                ),
                new SceneDevice(
                        (Scene) new Select().from(Scene.class).where("name='外出模式'").executeSingle(),
                        (Device) new Select().from(Device.class).where("name='智能摄像头'").executeSingle()
                ),
                new SceneDevice(
                        (Scene) new Select().from(Scene.class).where("name='睡眠模式'").executeSingle(),
                        (Device) new Select().from(Device.class).where("name='智能插座'").executeSingle()
                ),
                new SceneDevice(
                        (Scene) new Select().from(Scene.class).where("name='睡眠模式'").executeSingle(),
                        (Device) new Select().from(Device.class).where("name='智能摄像头'").executeSingle()
                ),
                new SceneDevice(
                        (Scene) new Select().from(Scene.class).where("name='派对模式'").executeSingle(),
                        (Device) new Select().from(Device.class).where("name='智能插座'").executeSingle()
                ),
                new SceneDevice(
                        (Scene) new Select().from(Scene.class).where("name='派对模式'").executeSingle(),
                        (Device) new Select().from(Device.class).where("name='微波炉'").executeSingle()
                ),
        };
        List<SceneDevice> data = new ArrayList<>(Arrays.asList(sceneDeviceData));
        for (SceneDevice each : data) {
            each.save();
        }
    }

    @Override
    protected void setUpActionBar() {
        super.setUpActionBar();
        // 设置标题
        mTvActionBarTitle.setText(getString(R.string.title_fragment_scene));
        // 设置添加情景按钮点击监听
        ImageView btnAddDevice = (ImageView) mActionBar.getCustomView().findViewById(R.id.btn_add_device);
        btnAddDevice.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivityForResult(new Intent(getActivity(), SceneAddActivity.class), ACTION_ADD_SCENE);
            }
        });
    }

    private void setUpSceneList() {
        mSceneList.setLayoutManager(new LinearLayoutManager(getActivity()));
        mAdapter = new SceneRecyclerViewAdapter(getActivity(), mSceneData);
        mSceneList.setAdapter(mAdapter);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case ACTION_ADD_SCENE:
                if (resultCode == Activity.RESULT_OK) {
                    updateSceneData(data);
                }
                break;
            default:
                break;
        }
    }

    private void updateSceneData(Intent data) {
        if (data != null) {
            Scene scene = (Scene) data.getExtras().getSerializable("new_scene");
            mSceneData.add(scene);
            // TODO: After scene add
            this.initData();
            setUpSceneList();
        }
    }
}
